package com.shamrock.cms.security;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.shamrock.cms.entity.Admin;
import com.shamrock.cms.service.AdminService;

@Service
public class MyUserDetailsService implements UserDetailsService{

	private Logger logger = Logger.getLogger(getClass());
	@Autowired
	private AdminService adminService;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		Admin user = adminService.getAdminByName(username);
		logger.info(user);
		if(null == user){
			throw new UsernameNotFoundException("user not found.");
		}
		List<GrantedAuthority> authorities = new ArrayList<>();
		String[] roles = user.getRoles().split(",");
		for(String role : roles){
			authorities.add(new SimpleGrantedAuthority(role));
		}
		logger.info(username+"'s roles:"+authorities);
		return  new User(user.getName(), user.getPassword(), authorities);
	}

}
